<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    img {
        width: 100px;
        height: 100px;
    }

    * {
        list-style: none;
    }
</style>

<body>
    <h2>购物车</h2>
    <ul>

    </ul>

    <h2><span class="money">0</span><button class="js">结算</button></h2>

    <script>
        var g = localStorage.getItem('gwc')
        var gwc = JSON.parse(g)
        console.log(gwc);

        function apply() {
            document.querySelector('ul').innerHTML = ''
            gwc.forEach(item => {
                document.querySelector('ul').innerHTML += `
                <span><input type="checkbox" ${item.is ? 'checked' : ''} onclick='dan(${item.id})'></span>
                <span><img src="${item.img}"></span>
                <span>${item.name}</span>
                <span>￥${item.price}</span>
                <span><button onclick=jian(${item.id})>-</button></span>
                <span>${item.num}</span>
                <span><button onclick=jia(${item.id})>+</button></span>
                `
            })
        }
        apply()

        function jia(id) {
            var a = gwc.findIndex(item => item.id == id)
            gwc[a].num++
            apply()
            zong()
        }

        function jian(id) {
            var a = gwc.findIndex(item => item.id == id)
            if (gwc[a] != 0) {
                gwc[a].num--
            }
            apply()
            zong()
        }

        var money = document.querySelector('.money')
        function zong() {
            var zong = 0
            gwc.forEach(item => {
                if (item.is) {
                    zong += item.price * item.num
                }
            })
            money.innerHTML = zong
        }

        function dan(id) {
            var i = gwc.findIndex(item => item.id == id)
            gwc[i].is = event.target.checked
            zong()
        }

        document.querySelector('.js').addEventListener('click', () => {
            localStorage.setItem('jsym', JSON.stringify(gwc))
            location.assign('./2.28机试结算页面.html')
        })
        
        

    </script>
</body>

</html>